#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>

#include "tp_socket.h"

void diep(char *s) {
    perror(s);
    exit(1);
}

int cl_handle(int cl_sock, int bsize){
    /* Recebe o nome do arquivo */
    char* buffer;
    buffer = (char*)malloc(sizeof(char)*bsize);
    char fileName[256];

    int i=0;
    buffer[0] = ' ';  
    while ( buffer[0] != '\0' ){
        if (recv(cl_sock, buffer, 1, 0) < 0) 
            diep("recv");
        fileName[i++] = buffer[0];
    }
    fileName[i] = '\0';

    //abre o arquivo
    FILE *fileIn;
    if( (fileIn = fopen(fileName,"r")) == NULL ){
        close(cl_sock);
        perror("fopen");
        return -1;
    }
    printf("File Open: %s\n", fileName);
    //

    /* Envia o arquivo para o cliente */
    int bytes = 0;
    int sended = 0;
    while ( (bytes = fread(buffer,1,bsize, fileIn)) > 0 ){ 
        if ( send(cl_sock, buffer, bytes,0) < 0)
            diep("send"); 

        sended += bytes;
    }

    /* Fecha a conexao com o cliente */
    fclose(fileIn);
    close(cl_sock);
    return sended;
}

int main(int argc, char** argv){
    //tempo inicio
    struct timeval tv;
    double curtime;
    gettimeofday(&tv,NULL);
    curtime= tv.tv_sec + (tv.tv_usec/1000000.0);
    //

    if (argc < 3){
        printf("./servidor porto_servidor tam_buffer\n");
        exit(1);
    }

    tp_init();

    //Atribuição de Parametros
    unsigned short int serv_port;
    serv_port = htons(atoi(argv[1]));

    int buffer_size = atoi(argv[2]);

    //declaração do socket
    int sv_sock;
    struct sockaddr_in sv_addrin, cl_addrin;

    //Construção da estrutura sockaddr
    tp_build_addr(&sv_addrin, NULL, serv_port);

    if ((sv_sock = tp_socket(serv_port)) < 0)
        diep("socket");
        
    //aguarda conexão dos clientes
    char* buffer;
    buffer = (char*)malloc(sizeof(char)*buffer_size);
    int i;
    for(i=0;i<10;i++){
        if (tp_recvfrom(sv_sock, buffer, buffer_size, &cl_addrin) < 0)
            diep("recvfrom");
        printf("Received packet from %s:%d\nData: %s\n\n",inet_ntoa(cl_addrin.sin_addr), ntohs(cl_addrin.sin_port), buffer);
    }

    close(sv_sock);
    exit(0);
}
